<template>
  <div class="imgUpLoad">
    <ul>
      <li v-for="(item,index) in fileList" :key="index" :class="{mini: mini, large: large}" :style="shape==='rectangle'?'width:218px':''">
        <div v-if="item.imgUrl !== '无' && item.imgUrl !== '五'" class="pdf-bord" :class="{showImg: !item.showProgress}">
          <iframe :src="item.preieImgUrl" frameborder="0" scrolling="no" />
        </div>
        <div v-else class="other-img" :class="readOnly ? '' : deleteFile(index)" />
        <el-progress v-show="item.showProgress" :stroke-width="8" type="circle" :width="processWidth" :percentage="item.progress" />
        <div v-show="!item.showProgress && item.imgUrl !== '无' && item.imgUrl !== '五'" class="operate">
          <span title="预览" @click="viewImg(item.imgUrlPre)"><i class="el-icon-view" /></span>
          <span v-if="readOnly" title="下载" @click="downLoadHandle(item)"><i class="el-icon-download" /></span>
          <span v-if="!readOnly"><i title="删除" class="el-icon-delete" @click="deleteFile(index)" /></span>
        </div>
      </li>
      <li v-show="fileList.length < limitSize && !readOnly" :class="{mini: mini, large: large, card1: card1, card2: card2}" :style="shape==='rectangle'?'width:218px':''">
        <i class="el-icon-plus" />
        <div class="up-text">点击上传</div>
        <input type="file" multiple="multiple" @change="startUpload(0)">
      </li>
    </ul>
    <transition name="el-fade-in-linear">
      <div v-show="viewBoxShow" class="w-view">
        <div class="w-view-contain">
          <div class="pdf-view" :style="{ transform: `rotate(${rotateV}deg)` }">
            <iframe ref="iframeView" :src="currentViewImg" frameborder="0" scrolling="no" />
          </div>
        </div>
        <div class="black" @click="viewBoxShow = false" />
      </div>
    </transition>
  </div>
</template>

<script>
import axios from 'axios'
const ossUrl = process.env.VUE_APP_BASE_file_prew_url || 'http://test.img.yirunscm.com/'
import { fileDownloadAction } from '@/utils/commonUtil'
import { getToken } from '@/utils/auth'
export default {
  name: 'FileUpLoad',
  props: {
    value: {
      type: String,
      default: ''
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    mini: {
      type: Boolean,
      default: false
    },
    large: {
      type: Boolean,
      default: true
    },
    shape: {
      type: String,
      default: 'square'
    },
    card1: {
      type: Boolean,
      default: false
    },
    card2: {
      type: Boolean,
      default: false
    },
    limitType: {
      type: String,
      default: ''
    },
    maxFileSize: {
      type: Number,
      default: 50
    },
    limitSize: {
      type: Number,
      default: 1
    },
    tips: {
      type: String,
      default: ''
    },
    imageName: {
      type: String,
      default: ''
    },
    unLoad: {
      type: Boolean,
      default: true
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    uploadUrl: {
      type: String,
      default: '/fsmc/fsc/upload'
    },
    downLoadUrl: {
      type: String,
      default: '/fsmc/fsc/download'
    }
  },
  data() {
    return {
      fileList: [],
      downLoadUrls: '',
      baseUrl: process.env.VUE_APP_BASE_Upload_api,
      currentViewImg: '',
      exportValue: '',
      currentViewType: 'img',
      viewBoxShow: false,
      rotateV: 0,
      scale: 1,
      fileVersionUrl: '',
      previewUrl: '',
      currentIndex: 0
    }
  },
  computed: {
    processWidth() {
      if (this.mini) {
        return 70
      } else if (this.large) {
        return 140
      } else {
        return 110
      }
    }
  },
  watch: {
    value(newV, oldV) {
      if (newV !== oldV) {
        this.reset()
      }
    }
  },
  mounted() {
    this.reset()
  },
  methods: {
    downLoadHandle(item) {
      fileDownloadAction(item.imgUrl)
    },
    reset() {
      this.fileList.splice(0, this.fileList.length)
      if (this.value) {
        this.fileList.push({
          imgUrl: this.exportValue || this.value,
          imgUrlPre: this.value.split('http://preview.yirunscm.com/onlinePreview').length > 1 ? this.value : this.tranlateMethod(this.value),
          preieImgUrl: this.previewUrl,
          downLoadUrls: this.downLoadUrls,
          showProgress: false,
          progress: 0,
          lastName: ''
        })
      }
    },

    viewImg(imgUrl) {
      const iframe = this.$refs.iframeView
      iframe.style.height = iframe.parentNode.parentNode.offsetHeight - 40 + 'px'
      this.rotateV = 0
      this.currentViewImg = imgUrl
      this.viewBoxShow = true
    },

    changeImg(dir) {
      if (this.currentIndex > 0 && !dir) {
        this.currentIndex -= 1
        this.currentViewImg = this.fileList[this.currentIndex].imgUrl
        this.needChangeReset()
      } else if (this.currentIndex < (this.fileList.length - 1) && dir) {
        this.currentIndex += 1
        this.currentViewImg = this.fileList[this.currentIndex].imgUrl
        this.needChangeReset()
      }
    },

    needChangeReset() {
      const lastName = this.currentViewImg.substr(this.currentViewImg.lastIndexOf('.') + 1, this.currentViewImg.length).toUpperCase()
      if (lastName !== 'PDF') {
        this.currentViewType = 'img'
        if (this.$refs.myimgbox) this.$refs.myimgbox.reset()
      } else {
        this.currentViewType = 'pdf'
        setTimeout(() => {
          const iframe = this.$refs.iframeView
          iframe.style.height = iframe.parentNode.parentNode.offsetHeight - 40 + 'px'
        }, 10)
      }
    },

    deleteFile(index) {
      const imgUrl = this.fileList[index].imgUrl
      this.fileList.splice(index, 1)
      this.$emit('delete', imgUrl)
      this.exportFilesValue(imgUrl)
    },
    // 点击上传按钮
    startUpload(type, originFileObj) {
      const file = event.target
      let passed = true
      for (const f of file.files) {
        if (f.size / 1024 / 1024 > this.maxFileSize) {
          this.$message.error(`上传的文件不能大于${this.maxFileSize}M`)
          file.value = ''
          passed = false
          return
        }

        const exe = f.name.substr(f.name.lastIndexOf('.') + 1, f.name.length).toUpperCase()
        if (this.limitType && exe !== this.limitType.toUpperCase()) {
          this.$message.error(`只能上传${this.limitType}文件`)
          file.value = ''
          passed = false
          return
        }
        f['lastName'] = exe
        if (originFileObj) originFileObj.lastName = exe
      }

      if (passed) {
        if (type) {
          originFileObj.showProgress = true
          originFileObj.progress = 0
          this.uploadFile(originFileObj, file.files[0])
        } else {
          for (const f of file.files) {
            this.type = f.lastName
            if (this.limitSize > this.fileList.length) {
              const fileObj = {
                imgUrl: '',
                showProgress: true,
                progress: 0,
                lastName: f.lastName
              }
              this.fileList.push(fileObj)
              this.uploadFile(fileObj, f)
            }
          }
        }
        file.value = ''
      }
    },
    // 上传
    uploadFile(fileObj, file) {
      const _this = this
      const formData = new FormData()
      formData.append('file', file)
      fileObj.imgUrl = ''
      for (const k in this.data) {
        formData.append([k], this.data[k])
      }
      axios({
        url: this.baseUrl + this.uploadUrl,
        method: 'post',
        onUploadProgress: function(progressEvent) { // 原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            fileObj.progress = parseInt(progressEvent.loaded / progressEvent.total * 100)
          }
        },
        headers: { 'Authorization': 'bearer ' + getToken() || '', 'Content-Type': 'application/json', 'Tenant-Id': _this.$store.getters.tenantId },
        data: formData,
        withCredentials: true
      }).then(res => {
        if (res.data.code === 0) {
          setTimeout(() => {
            fileObj.showProgress = false
          }, 800)
          fileObj.imgUrl = this.tranlateMethod(res.data.data[0].fileVersion)
          this.$emit('change', res.data.data)
          this.exportFilesValue()
        } else {
          this.$message.error(res.errMsg)
        }
      })
    },
    tranlateMethod(val) {
      const urlId = val.split('==')
      let Purl = ''
      if (urlId.length > 1) {
        Purl = ossUrl + urlId[1]
      } else {
        Purl = this.downLoadUrl + '?id=' + val.id + '&access_token=' + getToken()
      }
      this.exportValue = val
      this.downLoadUrls = Purl
      this.previewUrl = 'http://preview.yirunscm.com/picview?width=200&height=150&url=' + encodeURIComponent(Base64.encode(Purl))
      return 'http://preview.yirunscm.com/onlinePreview?url=' + encodeURIComponent(Base64.encode(Purl))
    },
    exportFilesValue() {
      const noComplete = this.fileList.find(e => {
        return e.showProgress
      })
      if (noComplete) {
        setTimeout(() => {
          this.exportFilesValue()
        }, 200)
      } else {
        const files = []
        this.fileList.forEach(e => {
          files.push(e.imgUrl)
        })
        this.$emit('input', files.join(','))
      }
    }
  }
}

</script>
<style>
.pdf-view {
  height: 100%;
}
.other-img {
  position: relative;
  z-index: 99;
  background: url("../../assets/img/other-new.png") no-repeat;
  background-size: 50% 70%;
  background-position: 50% 40%;
  height: 100%;
  width: 100%;
  opacity: 0.5;
}
.pdf-view iframe {
  height: 100%;
}
.card1, .card2 {
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.card2 {
  background: url('../../assets/img/idcard-z.png');
}
.card1 {
  background: url('../../assets/img/idcard-f.png');
}
</style>
